<?php

namespace app\api\controller\timetable;
use app\common\controller\Api;
use app\admin\model\timetable\Usersetting;
use app\admin\model\timetable\Subjects;
use app\admin\model\timetable\Course;
use app\admin\model\timetable\Usercourse;
use think\Db;

class Incourse extends Base
{
    protected $noNeedLogin = ['getcode'];
    
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\timetable\Usercourse;
    }

    
    
    public function login()
    {
        $username = $this->request->param('username');
        $password = $this->request->param('password');
		$vccode = $this->request->param('vccode');//此处为验证码，如果学校教务系统没有验证码则无需该变量

        $schoolId = intval($this->request->param('schoolId'));
        $data = $this ->getData($username,$password,$vccode);
        if (empty($data)) {
            $this->error();
        }else {
            // timetable_course
            // timetable_subjects
            // timetable_usercourse
            $userid = $this->auth->id;
            $nums = array_column($data,'nums');
            array_multisort($nums,SORT_ASC,$data);

            foreach ($data as $i) {

                   if(empty($i['name'])){
                        continue;
                   }
                   $subject_id =  $this->getSubId($i['name'],$schoolId);
                   //开始写排课表（timetable_course_info表）
                    $courseinfo = [];
                    $courseinfo = $this->combineData($i);
                    $courseinfo['subject_id'] = $subject_id;
                    //先查是否已经有，如果有，引用即可
                    $inforow = Course::get($courseinfo);
                    if ($inforow) {
                        $ciid = $inforow['ciid'];
                    }else{
                        $myinforow = new Course();
                        $myinforow->save($courseinfo);
                        $ciid = $myinforow->ciid;
                    }
                //写最终的用户表，还需要查一遍，防止重复提交
                $user_course_info = Usercourse::get(['user_id' =>$userid, 'ciid' => $ciid]);
                if (!$user_course_info) {
                    Usercourse::create(['user_id'=>$userid,'ciid'=>$ciid]);
                }
            }

        $this->up_course_inf();
        $this->success('添加成功!');
        }
    }
 public function creat_course_inf($user_id){
        $where['user_id'] = $user_id;
        $list = $this->model->with(['timetablecourse.timetablesubjects'])
            ->where('user_id',$user_id)
            ->select();
        foreach ($list as $row) {
            $row['sname']=$row->timetablecourse->timetablesubjects->sname;
            $row->visible([
                'sname',
                'tname',
                'classroom',
                'days',
                'nums',
                'enum',
                'attend',
                'ciid',
                'subject_id'
            ]);
        }
        return json_encode($list);
    }
     public function up_course_inf(){
        $row = Usersetting::get($this->auth->id);
        $my_course_info = $this->creat_course_inf($this->auth->id);
        $lovers_course_info = '';
        //更新情侣课表
        if($row['lovers_id']){
            $lovers_course_info = $this->creat_course_inf($row['lovers_id']);
            $loversRow = new Usersetting();
            $loversRow->save([
                'my_course_info' => $lovers_course_info,
                'lover_course_info' => $my_course_info
            ],['user_id' => $row['lovers_id']]);
        }
        $row->save([
            'my_course_info'  => $my_course_info,
            'lover_course_info'  => $lovers_course_info,
        ]);
    }
    private function getData($username,$password){
        $data = file_get_contents("xxx.com/getinfo.php?username=$username&password=$password&vccode=$vocode");//此处为获取数据，tips:别忘了判断用户账户密码是否正确。
        $data = json_decode($data, true);
        return $data;
    }//API获取数据，需要自己适配（自由发挥）
    private function getSubId($name,$school_id){

                $subjectsinfo = Subjects::get(['sname' => $name,'school_id' =>$school_id]);

                if ($subjectsinfo) {
                    $subject_id = $subjectsinfo['subject_id'];
                }else{
                    //添加
                    $row = new Subjects([
                        'sname' => $name,
                        'school_id' => $school_id
                    ]);
                    $row->save();
                    $subject_id = $row->subject_id;
                }

                return $subject_id;

    }
    private function combineData($i){
         $courseinfo =[];
                    $courseinfo['tname'] = $i['teacher'];
                    $courseinfo['classroom'] =$i['room'];
                    
                    $courseinfo['days'] = 0===intval($i['days']) ? 7 :$i['days'];
                    $courseinfo['nums'] = $i['nums'];
                    //根据结束时间，转化为大小课
                    $courseinfo['enum'] = $i['enum'];
                    $courseinfo['attend'] = $i['attend'];

                    return  $courseinfo;

    }
    public function classresult()
    {
        $this->success();
    }

    public function inclass()
    {
        $this->success();
    }
    public function getcode(){
		//此处为GET验证码方法需要自己适配

    }
}
